package com.blockmeta.bbs.businesslibrary.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.businesslibrary.R;
import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import com.king.zxing.CaptureActivity;
import com.king.zxing.DecodeFormatManager;
import com.king.zxing.Intents;
import com.king.zxing.camera.FrontLightMode;
import com.king.zxing.util.CodeUtils;

public class CustomQrCodeActivity extends CaptureActivity implements View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {
    RelativeLayout mZxingBack;
    ImageView mZxingFlash;
    ImageView mZxingPic;
    public TakePhoto takePhoto;//图片选择框架
    private InvokeParam invokeParam;//图片选择

    @Override
    public int getLayoutId() {
        return R.layout.custom_capture_activity;
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        mZxingPic = findViewById(R.id.zxing_pic);
        mZxingFlash = findViewById(R.id.zxing_flash);
        mZxingBack = findViewById(R.id.zxing_back);
        mZxingPic.setOnClickListener(this);
        mZxingBack.setOnClickListener(this);
        qrScan();

    }

    private void qrScan() {
        getCaptureHelper()
                .decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)//设置只识别二维码会提升速度
                .playBeep(true)
                .vibrate(true)
                .supportVerticalCode(false)//支持扫垂直条码，建议有此需求时才使用。
                .fullScreenScan(true)
//                .decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)//设置只识别二维码会提升速度
//                .framingRectRatio(0.9f)//设置识别区域比例，范围建议在0.625 ~ 1.0之间。非全屏识别时才有效
//                .framingRectVerticalOffset(0)//设置识别区域垂直方向偏移量，非全屏识别时才有效
//                .framingRectHorizontalOffset(0)//设置识别区域水平方向偏移量，非全屏识别时才有效
                .frontLightMode(FrontLightMode.AUTO)//设置闪光灯模式
                .tooDarkLux(45f)//设置光线太暗时，自动触发开启闪光灯的照度值
                .brightEnoughLux(100f)//设置光线足够明亮时，自动触发关闭闪光灯的照度值
                .continuousScan(false)//是否连扫
                .supportLuminanceInvert(true);//是否支持识别反色码（黑白反色的码），增加识别率
    }



    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }


    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.zxing_back) {
            finish();

        } else if (vId == R.id.zxing_pic) {
            getTakePhoto().onPickFromGallery();
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        TImage image = result.getImage();
        String compressPath = image.getOriginalPath();
        LogUtils.i("author" + "返回图片路径地址=====" + compressPath);
        //异步解析
        asyncThread(new Runnable() {
            @Override
            public void run() {
                final String result = CodeUtils.parseCode(compressPath);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("author", "result:" + result);
                        Intent intent = new Intent();
                        intent.putExtra(Intents.Scan.RESULT, result);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                });

            }
        });
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(CustomQrCodeActivity.this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    private void asyncThread(Runnable runnable) {
        new Thread(runnable).start();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogUtils.i("author" + "返回图片路径地址=====msg:" + msg);

    }

    @Override
    public void takeCancel() {
        LogUtils.i("author" + "返回图片路径地址=====cancel");

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
